package com.cy.pj.sys.service.Impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.sys.common.vo.SysRoleMenuVo;
import com.cy.pj.sys.dao.SysRoleDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.pojo.PageObject;
import com.cy.pj.sys.pojo.SysRole;
import com.cy.pj.sys.pojo.User;
import com.cy.pj.sys.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private SysRoleDao roleDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;


    @Override
    public PageObject findPageObjects(String name, Integer pageCurrent) {
        if (pageCurrent == null || pageCurrent < 1)
            throw new IllegalArgumentException("页码无效");
        int rowCount = roleDao.getRowCount(name);
        if (rowCount == 0)
            throw new ServiceException("无记录");
        int pageSize = 2;
        int startIndex = (pageCurrent - 1) * pageSize;
        List<SysRoleDao> records = roleDao.findPageObjects(name, startIndex, pageSize);
        return new PageObject<>(pageCurrent, pageSize, rowCount, records);
    }

    @Override
    public int saveObject(SysRole entity, Integer[] menuIds) {
        if (entity == null)
            throw new ServiceException("保存对象不能为空");
        if (StringUtils.isEmpty(entity.getName()))
            throw new IllegalArgumentException("角色名不能为空");
        if (menuIds == null || menuIds.length == 0) {
            throw new ServiceException("为角色分配权限");
        }
        int rows = roleDao.insertObject(entity);
        sysRoleMenuDao.insertObjects(entity.getId(), menuIds);
        return rows;
    }

    @Override
    public SysRoleMenuVo findObjectById(Integer id) {
        if (id == null || id <= 0)
            throw new IllegalArgumentException("id值不合法");
        SysRoleMenuVo result = roleDao.findObjectById(id);
        if (result == null)
            throw new ServiceException("不存在此记录");
        return result;
    }


}
